package com.simple.editor.action.impl;

import com.simple.editor.ApplicationContext;
import com.simple.editor.action.ActionManager;
import com.simple.editor.action.EditorUIAction;
import com.simple.editor.callback.Callback;
import com.simple.editor.ui.FileModel;
import com.simple.editor.ui.InfoPane;

import java.util.List;

/**
 * {@link ActionManagerImpl} provides asynchronous implementation of {@link ActionManager}.
 * <p/>
 * <p/>
 * Created with IntelliJ IDEA.
 * User: vlad
 * Date: 6/2/13
 * Time: 5:08 PM
 * To change this template use File | Settings | File Templates.
 */
public class ActionManagerImpl implements ActionManager {
    private final ApplicationContext ctx;
    private final InfoPane infoPane;

    public ActionManagerImpl(final ApplicationContext context, final InfoPane infoPanel) {
        this.ctx = context;
        this.infoPane = infoPanel;
    }

    @Override
    public void runAction(final Callback callback, final EditorUIAction.Type actionId, final FileModel... files) {
        final Object comp = ctx.getComponent(actionId);
        if (comp instanceof EditorUIAction) {
            try {
                if (callback == null) {
                    ((EditorUIAction) comp).perform(files);
                } else {
                    ((EditorUIAction) comp).perform(callback, files);
                }
            } catch (Exception e) {
                infoPane.addError(String.format("Editor error: %s", e.getMessage()));
            }
        } else {
            throw new IllegalArgumentException("Unknown action id: " + actionId);
        }
    }

    @Override
    public void runAction(final EditorUIAction.Type actionId, final FileModel... files) {
        runAction(null, actionId, files);
    }

    @Override
    public void runAction(final EditorUIAction.Type actionId, final List<FileModel> files) {
        runAction(actionId, files.toArray(new FileModel[files.size()]));
    }

    @Override
    public void runAction(Callback callback, EditorUIAction.Type actionId, List<FileModel> files) {
        runAction(callback, actionId, files.toArray(new FileModel[files.size()]));
    }
}
